<template>
  <demo-content :title="title">
    <div>
      <p>
        HTML 元素的 <code>getBoundingClientRect</code> 函数获取的 x、y、宽、高
        都是包括 padding、border 在内的矩形的特性，其中的 x、y 是客户端坐标。
      </p>
      <ul>
        <li>Left canvas: ({{ point1.x }}, {{ point1.y }})</li>
        <li>Right canvas: ({{ point2.x }}, {{ point2.y }})</li>
      </ul>
    </div>
    <canvas
      ref="canvasRef"
      style="background-color: deepskyblue; padding: 30px; border; border: 15px solid orange;"
    ></canvas>
    <canvas
      ref="canvasRef2"
      style="background-color: deepskyblue; padding: 30px; border; border: 15px solid orange; height: 300px; width: 300px"
    ></canvas>
    <!-- <div style="height: 1300px; background-color: antiquewhite"></div> -->
  </demo-content>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { type Point, drawMosaic, clientPosCvt } from "./utils";

const title = "坐标转换";

// 指定组件上的属性
defineOptions({ title });

const canvasRef = ref<HTMLCanvasElement>();
const canvasRef2 = ref<HTMLCanvasElement>();

const point1 = ref<Point>({
  x: 0,
  y: 0,
});
const point2 = ref<Point>({
  x: 0,
  y: 0,
});

function redraw(ctx: CanvasRenderingContext2D, spot?: Point) {
  ctx.clearRect(0, 0, 300, 150);
  drawMosaic(ctx, { w: 50, color1: "#00a0ff" });
  if (spot?.x || spot?.y) {
    ctx.beginPath();
    ctx.moveTo(0, spot.y);
    ctx.lineTo(300, spot.y);
    ctx.moveTo(spot.x, 0);
    ctx.lineTo(spot.x, 150);
    ctx.stroke();
  }
}

onMounted(() => {
  const canvas = canvasRef.value!;
  const canvas2 = canvasRef2.value!;
  const ctx = canvas.getContext("2d")!;
  const ctx2 = canvas2.getContext("2d")!;

  redraw(ctx);
  redraw(ctx2);

  canvas.onmousemove = (e) => {
    point1.value = clientPosCvt(ctx, e);
    redraw(ctx, point1.value);
  };
  canvas2.onmousemove = (e) => {
    point2.value = clientPosCvt(ctx2, e);
    redraw(ctx2, point2.value);
  };
});
</script>

<style src="./default.css" scoped></style>
